// navptnpc.txt
// A hostile creature which will fight for a while and, when wounded, run to a
// given nav point. Fights to death once there.
// Memory Cells:
//   Cell 0 - Nav point it runs to.
//	 Cell 1 - Does it fidget? If 0, yes. If 1, no.
//   Cell 2,3 - SDF to increment when it is killed.
//	 Cell 4 - Node when talked to, 0 for none

begincreaturescript;

variables;

short i,target;
short has_fled = 0;
short hit_count = 0;
short flee_mess = 0;

body;

beginstate INIT_STATE;
	break;

beginstate DEAD_STATE;
	if ((get_memory_cell(2) != 0) || (get_memory_cell(3) != 0))
		inc_flag(get_memory_cell(2),get_memory_cell(3),1);
break;

beginstate START_STATE; 
	// if I have a target for some reason, go attack it
	if (target_ok()) {
		if (dist_to_char(get_target()) <= 16)
			set_state(3);
			else set_foe_target(ME,-1);
		}
	
	if (get_foe_target(ME,8,0)) {
		do_attack();
		set_state(3);
		}
	if (who_shot_me() >= 0) {
		set_foe_target(ME,who_shot_me());
		do_attack();
		set_state(3);
		}
	

	if ((get_health(ME) < (1 * get_max_health(ME)) / 2) &&
	  (has_fled == 0)) {
		if (flee_mess == 0) {
			flee_mess = 1;
			print_named_str(ME,"runs away!");
			}
		has_fled = 1;
		approach_nav_point(ME,get_memory_cell(0),3);
		set_state(4);
		}

	if ((has_fled > 0) && (dist_to_nav_point(ME,get_memory_cell(0)) > 5))
		approach_nav_point(ME,get_memory_cell(0),3);
		else if ((has_fled == 0) && (my_dist_from_start() >= 8)) 
			return_to_start(ME,1);
			else if (get_memory_cell(1) == 0)
				fidget(ME,20);

	if (am_i_doing_action() == FALSE)
		end_combat_turn();
break;

beginstate 3; // attacking
	if ((get_health(ME) < (get_max_health(ME)) / 2) &&
	  (has_fled == 0)) {
		if (flee_mess == 0) {
			flee_mess = 1;
			print_named_str(ME,"runs away!");
			}

		has_fled = 1;
		set_foe_target(ME,-1);
		set_act_at_dist(ME,1);
		approach_nav_point(ME,get_memory_cell(0),3);
		set_state(4);
		}

	if (target_ok() == FALSE)
		set_state(START_STATE);
	do_attack();
break;

beginstate 4; // fleeing state
	 set_act_at_dist(ME,1);
	 
	 if (who_shot_me() >= 0) 
		hit_count = hit_count + 1;
	if (hit_count >= 2)
		set_state(START_STATE);
		
	if (approach_nav_point(ME,get_memory_cell(0),3)) {
		set_foe_target(ME,-1);
		set_state(START_STATE);
		}
break;


beginstate TALKING_STATE;
	if (get_memory_cell(4) == 0) {
		print_str("Talking: It doesn't respond.");
		}
		else begin_talk_mode(get_memory_cell(4));
break;